/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.tagservice.impl;

import com.lightkits.common.db.entity.BdTag;
import com.lightkits.common.db.entity.BdTagHistory;
import com.lightkits.common.db.entity.BdTagThing;
import com.lightkits.common.db.entity.BdTagThingHistory;
import com.lightkits.common.db.entity.FndLocationBase;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.utility.date.DateUtil;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.soa.client.id.GetGlobalIDRequestType;
import com.lightkits.framework.soa.client.id.GetGlobalIDResponseType;
import com.lightkits.framework.soa.client.id.IDServiceClient;
import com.lightkits.wms.domain.tagservice.CreateTagParamsService;
import com.lightkits.wms.domain.tagservice.model.TagDTO;
import com.lightkits.wms.dto.tagservice.model.CancelTagDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;


/**
 * CreateTagParamsServiceImpl
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/5/22 16:04
 */
@Service
public class CreateTagParamsServiceImpl implements CreateTagParamsService {
    private final Logger logger = LoggerFactory.getLogger(CreateTagParamsServiceImpl.class);

    private final IDServiceClient idServiceClient;

    @Autowired
    public CreateTagParamsServiceImpl(IDServiceClient idServiceClient) {
        this.idServiceClient = idServiceClient;
    }

    /**
     * 创建条码
     *
     * @param dtos 条码参数
     * @return BdTag
     **/
    @Override
    public List<BdTag> createBdTag(List<TagDTO> dtos) {
        List<BdTag> tags = new ArrayList<>();
        GetGlobalIDRequestType idRequest = new GetGlobalIDRequestType();
        idRequest.setCount(dtos.size());
        GetGlobalIDResponseType idResponse = idServiceClient.getGlobalId(idRequest);
        Iterator<Long> sfIds = idResponse.getIds().iterator();
            dtos.forEach(dto -> {
                BdTag tag = new BdTag();
                //根据条码ID赋值
                if (ObjectUtil.isEmpty(dto.getTagId())) {
                    tag.setId(sfIds.next());
                } else {
                    tag.setId(dto.getTagId());
                }
                //根据是否有tagId判断新增还是修改
                if (ObjectUtil.isEmpty(dto.getTagId())) {
                    //根据条码类型取得条码状态
                    if (dto.getTagType().equals("1U1S")
                            || dto.getTagType().equals("1U1T")) {
                        dto.setTagStatus("TAKEN");
                        tag.setTagStatus("TAKEN");
                    } else {
                        tag.setTagStatus("EMPTY");
                        dto.setTagStatus("EMPTY");
                    }
                } else {
                    tag.setTagStatus(dto.getTagStatus());
                }
                tag.setTagType(dto.getTagType());
                tag.setOwnerOrganizationId(dto.getOwnerOrgId());
                tag.setTagCode(dto.getTagCode());
                tag.setVerificationCode(dto.getVerificationCode());
                tag.setDCode(dto.getDCode());
                tag.setProductCode(dto.getProductCode());
                tag.setStorageUnitCode(dto.getStorageUnitCode());
                tag.setCapacityQty(dto.getCapacityQty());
                tag.setOuterTagId(dto.getOuterTagId());
                tag.setResourceId(dto.getResourceId());
                tag.setLocationId(dto.getLocationId());
                tag.setWarehouseId(dto.getWarehouseId());
                tag.setWmAreaId(dto.getWmAreaId());
                tag.setContainerId(dto.getContainerId());
                tag.setContainerType(dto.getContainerType());
                tag.setDocumentTypeId(dto.getDocumentTypeId());
                tag.setDocumentId(dto.getDocumentId());
                tag.setContainerOwnerId(dto.getContainerOwnerId());
                tag.setContainerOwnerType(dto.getContainerOwnerType());
                tag.setRemark(dto.getRemark());
                tags.add(tag);
            });
        return tags;
    }

    /**
     * 创建条码历史纪录
     *
     * @param dtos 条码参数
     * @param tags 条码
     * @return BdTagHistory
     **/
    @Override
    public CheckResult<List<BdTagHistory>> createBdTagHistory(List<TagDTO> dtos, List<BdTag> tags) {
        CheckResult<List<BdTagHistory>> checkResult = new CheckResult<>();
        List<BdTagHistory> tagHistories = new ArrayList<>();
        checkResult.setSuccessful(true);
        try {
            for (TagDTO dto : dtos) {
                BdTagHistory tagHistory = new BdTagHistory();
                if (ObjectUtil.isEmpty(dto.getEventId())) {
                    continue;
                }
                Optional<BdTag> opt = tags.stream().filter(target ->
                        target.getTagCode().equals(dto.getTagCode())).findFirst();
                tagHistory.setTagId(opt.get().getId());
                tagHistory.setTagType(dto.getTagType());
                tagHistory.setEventId(dto.getEventId());
                tagHistory.setEventBy(dto.getEventBy());
                tagHistory.setEventTime(dto.getEventTime());
                tagHistory.setOwnerOrganizationId(dto.getOwnerOrgId());
                tagHistory.setTagCode(dto.getTagCode());
                tagHistory.setVerificationCode(dto.getVerificationCode());
                tagHistory.setDCode(dto.getDCode());
                FndLocationBase locationBase = new FndLocationBase().selectById(dto.getLocationId());
                if (locationBase != null) {
                    tagHistory.setLocationCode(locationBase.getLocationCode());
                }
                tagHistory.setProductCode(dto.getProductCode());
                tagHistory.setCapacityQty(dto.getCapacityQty());
                tagHistory.setOuterTagId(dto.getOuterTagId());
                tagHistory.setTagStatus(dto.getTagStatus());
                tagHistory.setResourceId(dto.getResourceId());
                tagHistory.setContainerId(dto.getContainerId());
                tagHistory.setContainerType(dto.getContainerType());
                tagHistory.setDocumentTypeId(dto.getDocumentTypeId());
                tagHistory.setDocumentId(dto.getDocumentId());
                tagHistory.setContainerOwnerId(dto.getContainerOwnerId());
                tagHistory.setContainerOwnerType(dto.getContainerOwnerType());
                tagHistory.setRemark(dto.getRemark());
                tagHistories.add(tagHistory);
            }
            checkResult.setData(tagHistories);
        } catch (Exception e) {
            logger.error("create Bd Tag History.error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

    /**
     * 创建条码历史纪录
     *
     * @param dtos 条码
     * @param tags 取消条码参数
     * @return BdTagHistory
     */
    @Override
    public CheckResult<List<BdTagHistory>> createCanBdTagHistory(List<BdTag> dtos, List<CancelTagDto> tags) {
        CheckResult<List<BdTagHistory>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        List<BdTagHistory> bdTagHistories = new ArrayList<>();
        try {
            for (BdTag dto : dtos) {

                Optional<CancelTagDto> opt = tags.stream().filter(target ->
                        target.getTagCode().equals(dto.getTagCode())).findFirst();
                if (ObjectUtil.isEmpty(opt.get().getEventId())) {
                    continue;
                }
                BdTagHistory tagHistory = new BdTagHistory();
                tagHistory.setTagType(dto.getTagType());
                tagHistory.setEventId(opt.get().getEventId());
                tagHistory.setTagId(dto.getId());
                tagHistory.setEventBy(opt.get().getEventBy());
                tagHistory.setEventTime(DateUtil.toDate(opt.get().getEventTime()));
                tagHistory.setEventId(opt.get().getEventId());
                tagHistory.setOwnerOrganizationId(dto.getOwnerOrganizationId());
                tagHistory.setTagCode(dto.getTagCode());
                tagHistory.setVerificationCode(dto.getVerificationCode());
                tagHistory.setDCode(dto.getDCode());
                FndLocationBase locationBase = new FndLocationBase().selectById(dto.getLocationId());
                if (locationBase != null) {
                    tagHistory.setLocationCode(locationBase.getLocationCode());
                }
                tagHistory.setProductCode(dto.getProductCode());
                tagHistory.setCapacityQty(dto.getCapacityQty());
                tagHistory.setOuterTagId(dto.getOuterTagId());
                tagHistory.setTagStatus(dto.getTagStatus());
                tagHistory.setResourceId(dto.getResourceId());
                tagHistory.setContainerId(dto.getContainerId());
                tagHistory.setContainerType(dto.getContainerType());
                tagHistory.setDocumentTypeId(dto.getDocumentTypeId());
                tagHistory.setDocumentId(dto.getDocumentId());
                tagHistory.setContainerOwnerId(dto.getContainerOwnerId());
                tagHistory.setContainerOwnerType(dto.getContainerOwnerType());
                tagHistory.setRemark(dto.getRemark());
                bdTagHistories.add(tagHistory);
            }

            checkResult.setData(bdTagHistories);
        } catch (Exception e) {
            logger.error("create Bd Tag History.error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

    /**
     * 创建实物条码
     *
     * @param dtos 条码参数
     * @param tags 条码
     * @return BdTagThing
     */

    @Override
    public CheckResult<List<BdTagThing>> createBdTagThing(List<TagDTO> dtos, List<BdTag> tags) {
        CheckResult<List<BdTagThing>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        List<BdTagThing> tagThings = new ArrayList<>();
        GetGlobalIDRequestType idRequest = new GetGlobalIDRequestType();
        idRequest.setCount(dtos.size());
        GetGlobalIDResponseType idResponse = idServiceClient.getGlobalId(idRequest);
        Iterator<Long> sfIds = idResponse.getIds().iterator();
        try {
            for (TagDTO dto : dtos) {
                BdTagThing tagThing = new BdTagThing();
                //修改时物料id和实物条码id不能全为空
                if (ObjectUtil.isEmpty(dto.getTagThingId()) && ObjectUtil.isEmpty(dto.getItemId())) {
                    continue;
                }
                if (ObjectUtil.isEmpty(dto.getTagThingId())) {
                    tagThing.setId(sfIds.next());
                } else {
                    tagThing.setId(dto.getTagThingId());
                }
                Optional<BdTag> opt = tags.stream().filter(target ->
                        target.getTagCode().equals(dto.getTagCode())).findFirst();
                tagThing.setTagThingType(dto.getTagThingType());
                tagThing.setTagId(opt.get().getId());
                tagThing.setInnerTagId(dto.getInnerTagId());
                tagThing.setItemId(dto.getItemId());
                tagThing.setUom(dto.getUomCode());
                tagThing.setQuantity(dto.getQuantity());
                tagThing.setPrimaryUom(dto.getPrimaryUomCode());
                tagThing.setPrimaryQuantity(dto.getPrimaryQuantity());
                tagThing.setLotNumber(dto.getLotNumber());
                tagThing.setOwnerId(dto.getOwnerId());
                tagThing.setOwnerType(dto.getOwnerType());
                tagThing.setQcStatus(dto.getQcStatus());
                tagThing.setQcRemark(dto.getQcRemark());
                tagThings.add(tagThing);
            }

            checkResult.setData(tagThings);
        } catch (Exception e) {
            logger.error("create Bd Tag Thing.error", e);
            throw new LightKitsBizException(e.getMessage());
        }
        return checkResult;
    }

    /**
     * 创建实物条码历史记录
     *
     * @param dtos      条码参数
     * @param tagThings 实物条码参数
     * @param tags      条码
     * @return BdTagThingHistory
     */
    @Override
    public CheckResult<List<BdTagThingHistory>> createBdTagThingHistory(List<TagDTO> dtos,
                                                                        List<BdTagThing> tagThings,
                                                                        List<BdTag> tags) {
        CheckResult<List<BdTagThingHistory>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        List<BdTagThingHistory> tagThingHistories = new ArrayList<>();
        try {
            for (TagDTO dto : dtos) {

                //事件ID不为空下创建实物条码历史纪录
                if (!ObjectUtil.isEmpty(dto.getEventId())) {
                    continue;
                }
                BdTagThingHistory bdTagThingHistory = new BdTagThingHistory();
                Optional<BdTag> opt = tags.stream().filter(target ->
                        target.getTagCode().equals(dto.getTagCode())).findFirst();
                bdTagThingHistory.setTagId(opt.get().getId());
                Optional<BdTagThing> opt1 = tagThings.stream().filter(target ->
                        target.getTagId().equals(dto.getTagId())).findFirst();
                bdTagThingHistory.setTagThingId(opt1.get().getId());
                bdTagThingHistory.setEventBy(dto.getEventBy());
                bdTagThingHistory.setEventTime(dto.getEventTime());
                bdTagThingHistory.setEventId(dto.getEventId());
                bdTagThingHistory.setTagThingType(dto.getTagThingType());
                bdTagThingHistory.setInnerTagId(dto.getInnerTagId());
                bdTagThingHistory.setItemId(dto.getItemId());
                bdTagThingHistory.setUom(dto.getUomCode());
                bdTagThingHistory.setQuantity(dto.getQuantity());
                bdTagThingHistory.setPrimaryUom(dto.getPrimaryUomCode());
                bdTagThingHistory.setPrimaryQuantity(dto.getPrimaryQuantity());
                bdTagThingHistory.setLotNumber(dto.getLotNumber());
                bdTagThingHistory.setOwnerId(dto.getOwnerId());
                bdTagThingHistory.setOwnerType(dto.getOwnerType());
                bdTagThingHistory.setQcStatus(dto.getQcStatus());
                bdTagThingHistory.setQcRemark(dto.getQcRemark());
                tagThingHistories.add(bdTagThingHistory);
            }

            checkResult.setData(tagThingHistories);
        } catch (Exception e) {
            logger.error("create Bd Tag Thing History.error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }
}
